<template>
  <view class="wrap" @tap="inputBlur">
    <view class="headers">
      <img class="img" src="https://ainengli.hzjrsw.com/jkhx/drugBg.png" alt="" />
    </view>
    <scroll-view :scroll-top="scrollTop" class="scroll-Y" scroll-y="true">
      <view class="content">
        <view
          :class="['content-item', item.moveShow == true ? 'on' : '']"
          v-for="(item, index) in state.list"
          :key="index"
        >
          <view class="item">
            <view class="header">
              <view class="headerWrap">
                <text class="border"></text>
                <view class="title">药品{{ index + 1 }}</view>
                <icon
                  v-if="state.list && state.list.length != 1"
                  type=""
                  @tap="deleteFun(item, index)"
                  class="iconfont icon-shanchu1 img"
                ></icon>
              </view>
            </view>
            <view class="min">
              <view class="name">
                <text class="name-after">*</text>
                <text class="name-item">药品名称</text>
              </view>
              <view class="name-input on">
                <view class="input-view">
                  <input
                    @click.stop="inputClick(item, index)"
                    @blur="inputBlurTwo(item, index)"
                    v-model="item.drugName"
                    class="input"
                    type="text"
                    placeholder="请输入"
                  />
                </view>
                <text
                  type=""
                  class="iconfont icon-qingchu1 uni-icon"
                  v-if="item.drugName"
                  @click="clearIcon(item)"
                ></text>
                <!-- <text type="" @tap="scanCode(item, index)" class="iconfont icon-xiangji1 img" ></text> -->
                <view
                  :class="['nameList', state.nameListArray.length <= 1 ? '' : 'on']"
                  v-if="item.show"
                >
                  <view v-if="state.nameListArray && state.nameListArray.length > 0">
                    <view
                      class="name-item"
                      v-for="(itemTwo, keyboard) in state.nameListArray"
                      :key="keyboard"
                      @click.stop="selectName(item, itemTwo, index, keyboard)"
                    >
                      {{ itemTwo.drugName }}
                    </view>
                  </view>
                  <view v-else class="name-item-no">暂无数据</view>
                </view>
              </view>
              <view class="name">
                <text class="name-after">*</text>
                <text class="name-item">频率和用量</text>
              </view>
              <view class="name-input active">
                <view class="input-wrap" @tap="dosageClick(item, index)">
                  <input
                    v-model="item.diastolic"
                    class="input dosage"
                    disabled
                    type="text"
                    placeholder="请输入"
                    style="pointer-events: none"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="authenticationBtn">
      <view class="wraps">
        <view class="cancel" @tap="addFun">继续添加</view>
        <view class="goAuthentication" @tap="save">保存</view>
      </view>
    </view>
    <up-picker
      v-model="state.diastolicValue"
      :show="state.showName"
      :defaultIndex="state.defaultIndex"
      class="dosagePicker"
      title="频率和用量"
      :columns="state.columns"
      @confirm="diastolicConfirm"
      @close="diastolicClose"
      @cancel="diastolicClose"
      :closeOnClickOverlay="true"
    ></up-picker>
    <up-modal
      :show="state.showModal"
      :title="state.titleModal"
      :closeOnClickOverlay="true"
      @close="closeModal"
      @confirm="confirmModal"
    ></up-modal>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { infoAll, frequency, infoUnit, infoSave, drugInfoGet } from '@/api/hmm'
import { onShow } from '@dcloudio/uni-app'

const scrollTop = ref(0)
const state = reactive({
  showName: false,
  columns: [
    [],
    ['一'],
    ['次'],
    [
      '0.25',
      '1/3',
      '0.5',
      '0.75',
      '1',
      '1.25',
      '1.5',
      '1.75',
      '2',
      '2.25',
      '2.5',
      '2.75',
      '3',
      '3.25',
      '3.5',
      '3.75',
      '4',
      '4.5',
      '5',
      '5.5',
      '6',
      '6.5',
      '7',
      '7.5',
      '8',
      '8.5',
      '9',
      '9.5',
      '10',
      '10.5',
      '11',
      '11.5',
      '12',
      '12.5',
      '13',
      '13.5',
      '14',
      '14.5',
      '15',
      '15.5',
      '16',
      '16.5',
      '17',
      '17.5',
      '18',
      '18.5',
      '19',
      '19.5',
      '20',
      '21',
      '22',
      '23',
      '24',
      '25',
      '26',
      '27',
      '28',
      '29',
      '30',
      '31',
      '32',
      '33',
      '34',
      '35',
      '36',
      '37',
      '38',
      '39',
      '40',
      '41',
      '42',
      '43',
      '44',
      '45',
      '46',
      '47',
      '48',
      '49',
      '50'
    ],
    []
  ],
  isClick: false,
  isClickTwo: false,
  defaultIndex: [],
  list: [],
  deleteIndex: 0,
  dosageIndex: 0,
  dosageObj: {},
  scanIndex: 0,
  scanObj: {},
  showModal: false,
  titleModal: '确认删除?',
  nameList: [],
  nameListArray: [],
  nameListArrayTwo: [],
  inputIndex: 0,
  inputIndexNew: 0,
  inputObj: {},
  userInfo: {}
})
onShow(async () => {
  state.userInfo = uni.getStorageSync('userInfo')
    ? JSON.parse(uni.getStorageSync('userInfo')).patientInfo
    : {}
  await drugInfoGetFun()
  await init()
})
watch(
  () => state.list && state.list[state.inputIndexNew] && state.list[state.inputIndexNew].drugName,
  (newValue, oldValue) => {
    if (newValue) {
      state.nameListArray = state.nameList.filter((itemTwo) => {
        return itemTwo.drugName.includes(newValue)
      })
    } else {
      state.nameListArray = state.nameList
    }
  },
  {
    immediate: true,
    deep: true
  }
)
const drugInfoGetFun = () => {
  state.list = []
  let obj = {
    empi: state.userInfo.empi,
    drugCode: '',
    drugName: '',
    spec: '',
    frequency: '',
    dosage: '',
    dosageUnit: '',
    diastolic: '',
    diastolicList: '',
    show: false,
    moveShow: true,
    id: ''
  }
  let drugEmpi = state.userInfo.empi
  drugInfoGet(drugEmpi).then((res) => {
    if (res.code == 0) {
      if (res.data && res.data.length > 0) {
        let dataList = res.data
        for (let i = 0; i < dataList.length; i++) {
          dataList[i].empi = state.userInfo.empi
          dataList[i].diastolic =
            dataList[i].frequency == null ||
            dataList[i].dosage == null ||
            dataList[i].dosageUnit == null
              ? ''
              : dataList[i].frequency + '一次' + dataList[i].dosage + dataList[i].dosageUnit
          dataList[i].diastolicList =
            dataList[i].frequency == null ||
            dataList[i].dosage == null ||
            dataList[i].dosageUnit == null
              ? ''
              : dataList[i].frequency +
                ';' +
                '一;' +
                '次;' +
                dataList[i].dosage +
                ';' +
                dataList[i].dosageUnit
          dataList[i].show = false
          dataList[i].drugCode = dataList[i].drugCode
          dataList[i].id = dataList[i].id
          if (i == 0) {
            dataList[i].moveShow = true
          } else {
            dataList[i].moveShow = false
          }
        }
        state.list = dataList
      } else {
        state.list.push(obj)
      }
    }
  })
}
const init = () => {
  uni.showLoading({
    title: '加载中'
  })
  infoAll({}).then((res) => {
    uni.hideLoading()
    if (res.code == 0) {
      if (res.data && res.data.length > 0) {
        state.nameList = res.data
        state.nameListArray = JSON.parse(JSON.stringify(res.data))
        state.nameListArrayTwo = JSON.parse(JSON.stringify(res.data))
      } else {
        state.nameList = []
        state.nameListArray = []
      }
    }
  })
  frequency({}).then((res) => {
    if (res.code == 0) {
      let dataList = res.data.map((item) => {
        return item.name
      })
      state.columns[0] = dataList
    }
  })
  infoUnit({}).then((res) => {
    if (res.code == 0) {
      let dataList = res.data.map((item) => {
        return item.name
      })
      state.columns[4] = dataList
    }
  })
}
const addFun = async () => {
  if (state.isClickTwo == true || state.isClick == true) {
    return false
  }
  let obj = {
    empi: state.userInfo.empi,
    drugCode: '',
    drugName: '',
    spec: '',
    frequency: '',
    dosage: '',
    dosageUnit: '',
    diastolic: '',
    diastolicList: '',
    show: false,
    moveShow: false,
    id: ''
  }
  await state.list.push(obj)
  let query = wx.createSelectorQuery()
  query
    .select('.content')
    .boundingClientRect((res) => {
      scrollTop.value = res.height
      state.isClickTwo = true
      setTimeout(() => {
        state.isClickTwo = false
      }, 200)
    })
    .exec()
}
const scrollTo = (e) => {
  console.log('滚动', e.detail)
}
// 点击删除 二次弹窗
// const deleteFun = (item, index) => {
//   if (state.list && state.list.length > 1) {
//     if (item.drugName == '' && item.diastolic == '') {
//       item.show = false
//       state.inputIndex = 0
//       state.inputIndexNew = 0
//       state.list.splice(index, 1)
//     } else {
//       state.deleteIndex = index
//       state.showModal = true
//     }
//   }
// }
const deleteFun = (item, index) => {
  if (state.list && state.list.length > 1) {
    item.show = false
    state.inputIndex = 0
    state.inputIndexNew = 0
    state.list.splice(index, 1)
    state.deleteIndex = index
    for (let i = 0; i < state.list.length; i++) {
      if (i == 0) {
        state.list[0].moveShow = true
      } else {
        state.list[i].moveShow = false
      }
    }
  }
}
const closeModal = () => {
  state.showModal = false
}
const confirmModal = () => {
  state.showModal = false
  if (state.list && state.list.length > 1) {
    state.list.splice(state.deleteIndex, 1)
  }
}
// 频率和用量事件
const scanCode = (item, index) => {
  state.scanObj = item
  state.scanIndex = index
  uni.scanCode({
    success: (res) => {
      uni.showModal({
        title: '扫码结果',
        content: res.result,
        showCancel: false
      })
    },
    fail: (err) => {
      console.error('扫码失败：' + err)
    }
  })
}
const dosageClick = (item, index) => {
  state.showName = true
  state.dosageIndex = index
  state.dosageObj = item
  if (item.diastolicList) {
    let dataList = item.diastolicList.split(';')
    let dataWrap = []
    if (state.columns[0].indexOf(dataList[0]) != -1) {
      dataWrap.push(state.columns[0].indexOf(dataList[0]))
    } else {
      dataWrap.push(0)
    }
    if (state.columns[1].indexOf(dataList[1]) != -1) {
      dataWrap.push(state.columns[1].indexOf(dataList[1]))
    } else {
      dataWrap.push(0)
    }
    if (state.columns[2].indexOf(dataList[2]) != -1) {
      dataWrap.push(state.columns[2].indexOf(dataList[2]))
    } else {
      dataWrap.push(0)
    }
    if (state.columns[3].indexOf(dataList[3]) != -1) {
      dataWrap.push(state.columns[3].indexOf(dataList[3]))
    } else {
      dataWrap.push(0)
    }
    if (state.columns[4].indexOf(dataList[4]) != -1) {
      dataWrap.push(state.columns[4].indexOf(dataList[4]))
    } else {
      dataWrap.push(0)
    }
    state.defaultIndex = dataWrap
  }
}
const diastolicClose = () => {
  state.showName = false
}
const diastolicConfirm = (e) => {
  state.showName = false
  let getValue = e.value
  state.list[state.dosageIndex].diastolic = getValue.join(',').replace(/,/g, '')
  state.list[state.dosageIndex].diastolicList = getValue.join(',').replace(/,/g, ';')
  state.list[state.dosageIndex].frequency = getValue[0]
  state.list[state.dosageIndex].dosage = getValue[3]
  state.list[state.dosageIndex].dosageUnit = getValue[4]
}

const inputBlurTwo = (item, index) => {
  for (let i = 0; i < state.nameList.length; i++) {
    if (item.drugName === state.nameListArrayTwo[i].drugName) {
      item.dosage = state.nameListArrayTwo[i].dosage
      item.dosageUnit = state.nameListArrayTwo[i].dosageUnit
      item.drugCode = state.nameListArrayTwo[i].drugCode
      item.drugName = state.nameListArrayTwo[i].drugName
      item.frequency = state.nameListArrayTwo[i].frequency
      item.spec = state.nameListArrayTwo[i].spec
      item.id = state.nameListArrayTwo[i].id
      item.diastolic =
        state.nameListArrayTwo[i].frequency == null ||
        state.nameListArrayTwo[i].dosage == null ||
        state.nameListArrayTwo[i].dosageUnit == null
          ? ''
          : state.nameListArrayTwo[i].frequency +
            '一次' +
            state.nameListArrayTwo[i].dosage +
            state.nameListArrayTwo[i].dosageUnit
      item.diastolicList =
        state.nameListArrayTwo[i].frequency == null ||
        state.nameListArrayTwo[i].dosage == null ||
        state.nameListArrayTwo[i].dosageUnit == null
          ? ''
          : state.nameListArrayTwo[i].frequency +
            ';' +
            '一;' +
            '次;' +
            state.nameListArrayTwo[i].dosage +
            ';' +
            state.nameListArrayTwo[i].dosageUnit
      return false
    } else {
      item.dosage = ''
      item.dosageUnit = ''
      item.drugCode = ''
      item.drugName = item.drugName
      item.frequency = ''
      item.spec = ''
      item.id = ''
      item.diastolic = ''
      item.diastolicList = ''
    }
  }
}
const clearIcon = (item) => {
  item.dosage = ''
  item.dosageUnit = ''
  item.drugCode = ''
  item.drugName = ''
  item.frequency = ''
  item.spec = ''
  item.id = ''
  item.diastolic = ''
  item.diastolicList = ''
}

const inputClick = (item, index) => {
  state.list[state.inputIndexNew].show = false
  state.inputIndex = index
  state.inputIndexNew = index
  item.show = true
  if (item.drugName) {
    state.nameListArray = state.nameList.filter((itemTwo) => {
      return itemTwo.drugName.includes(item.drugName)
    })
  } else {
    state.nameListArray = state.nameList
  }
}
const inputBlur = () => {
  //   setTimeout(() => {
  state.list[state.inputIndexNew].show = false
  state.inputIndexNew = 0
  state.inputIndex = 0
  //   }, 200)
}
const selectName = (item, itemTwo, index, keyboard) => {
  state.list[index].drugCode = itemTwo.drugCode
  state.list[index].drugName = itemTwo.drugName
  state.list[index].spec = itemTwo.spec
  state.list[index].frequency = itemTwo.frequency
  state.list[index].dosage = itemTwo.dosage
  state.list[index].dosageUnit = itemTwo.dosageUnit
  let diastolicName =
    item.frequency == null || item.dosage == null || item.dosageUnit == null
      ? ''
      : item.frequency + '一次' + item.dosage + item.dosageUnit
  state.list[index].diastolic = diastolicName
  let diastolicList = item.frequency + ';' + '一;' + '次;' + item.dosage + ';' + item.dosageUnit
  state.list[index].diastolicList = diastolicList
  item.show = false
}
const save = () => {
  if (state.isClick == true) {
    return false
  }
  uni.showLoading({
    title: '加载中'
  })
  let dataLists = []
  for (let i = 0; i < state.list.length; i++) {
    let obj = {}
    if (state.list[i].drugName == '') {
      uni.showToast({
        title: '药品名称不能为空',
        icon: 'none'
      })
      return false
    }
    if (state.list[i].diastolic == '') {
      uni.showToast({
        title: '频率和用量不能为空',
        icon: 'none'
      })
      return false
    }
    obj.empi = state.list[i].empi
    obj.drugCode = state.list[i].drugCode
    obj.drugName = state.list[i].drugName
    obj.spec = state.list[i].spec
    obj.frequency = state.list[i].frequency
    obj.dosage = state.list[i].dosage
    obj.dosageUnit = state.list[i].dosageUnit
    dataLists.push(obj)
  }
  state.isClick = true
  infoSave(dataLists)
    .then((res) => {
      uni.hideLoading()
      if (res.code == 0) {
        uni.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 2000)
      }
    })
    .catch((err) => {
      state.isClick = false
    })
}
</script>

<style lang="scss" scoped>
.wrap {
  padding-bottom: calc(136rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(136rpx + env(safe-area-inset-bottom));
  min-height: 100vh;
  .headers {
    .img {
      display: block;
      height: 328rpx;
      width: 100%;
    }
  }
  .scroll-Y {
    height: calc(100vh - 356rpx);
    margin: -110rpx 32rpx 0;
    width: calc(100% - 64rpx);
  }
  .content {
    position: relative;
    z-index: 1;

    .content-item {
      margin-top: 32rpx;
      &:nth-child(1) {
        margin-top: 0;
      }
      &:nth-last-child(1) {
        padding-bottom: 32rpx;
        .item {
          .min {
            .name-input {
              .nameList {
                top: -370rpx;
                left: 0;
                min-height: 160rpx;
                max-height: 440rpx;
              }
            }
          }
        }
      }
      &:nth-last-child(1).on {
        .item {
          .min {
            .name-input {
              .nameList {
                top: 90rpx;
                height: 360rpx;
              }
            }
          }
        }
      }
      .item {
        .header {
          padding: 0 32rpx;
          position: relative;
          border-top-left-radius: 16rpx;
          border-top-right-radius: 16rpx;
          background: #fff;
          height: 100rpx;
          line-height: 100rpx;
          .headerWrap {
            height: 100%;
            border-bottom: 1rpx solid #e5e6eb;
          }
          .border {
            display: inline-block;
            vertical-align: middle;
            width: 8rpx;
            height: 32rpx;
            background: #00d1b6;
          }
          .title {
            display: inline-block;
            vertical-align: middle;
            font-size: 32rpx;
            color: #222;
            font-weight: 700;
            margin-left: 16rpx;
          }
          .img {
            float: right;
            color: #999999;
            font-size: 40rpx;
          }
        }
        .min {
          background: #fff;
          border-bottom-left-radius: 16rpx;
          border-bottom-right-radius: 16rpx;
          padding: 0 32rpx 64rpx;
          .name {
            height: 100rpx;
            line-height: 100rpx;
            .name-after {
              display: inline-block;
              vertical-align: middle;
              color: #ff503d;
              margin-right: 8rpx;
            }
            .name-item {
              display: inline-block;
              vertical-align: middle;
              color: #222;
              font-size: 32rpx;
              font-weight: 700;
            }
          }
          .name-input {
            height: 80rpx;
            line-height: 80rpx;
            position: relative;
            border: 1px solid #ebecef;
            border-radius: 8rpx;
            &.on {
              border: 0;
              border-radius: 0;
            }
            &.active {
              overflow: hidden;
            }
            .input-view {
              height: 80rpx;
              line-height: 80rpx;
              border: 1px solid #ebecef;
              border-radius: 8rpx;
              overflow: hidden;
            }
            .input {
              width: calc(100% - 80rpx);
              box-sizing: border-box;
              height: 100%;
              padding: 0 20rpx;
              background: #fff;

              &.dosage {
                width: 100%;
              }
            }
            .input-wrap {
              box-sizing: initial !important;
              height: 100%;
              .input {
                width: 100%;
              }
            }
            .img {
              position: absolute;
              top: 0;
              right: 0;
              font-size: 40rpx;
              color: #222;
              display: inline-block;
              padding: 0 20rpx;
            }
            .uni-icon {
              position: absolute;
              top: 1rpx;
              right: 6rpx;
              z-index: 999;
              font-size: 40rpx;
              display: block;
              line-height: 40rpx;
              text-align: center;
              padding: 18rpx 20rpx;
              background: #fff;
              color: #cfcfcf;
            }
            .nameList {
              position: absolute;
              top: 90rpx;
              left: 0;
              z-index: 999;
              background: #fff;
              border: 1rpx solid #e5e6eb;
              width: 100%;
              height: 360rpx;
              overflow-y: scroll;
              border-radius: 16rpx;
              .name-item {
                padding: 0 32rpx;
                border-bottom: 1px solid #f0f0f3;
                &:nth-last-child(1) {
                  border-bottom: 0;
                }
              }
              .name-item-no {
                padding: 0 32rpx;
                color: #666;
                font-size: 28rpx;
                display: block;
                text-align: center;
                margin-top: 40rpx;
              }
            }
          }
        }
      }
    }
  }
  .authenticationBtn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 3;
    background: #fff;
    border-top: 1rpx solid #ebecef;
    .wraps {
      padding: 0 32rpx;
      padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
      padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
      padding-top: 24rpx;
      text-align: center;
      font-size: 32rpx;
      color: #666;
      .cancel {
        width: calc(50% - 20rpx);
        display: inline-block;
        vertical-align: middle;
        margin-right: 24rpx;
        border: 1rpx solid #cfcfcf;
        transform: rotateZ(360deg);
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
      }
      .goAuthentication {
        width: calc(50% - 20rpx);
        display: inline-block;
        vertical-align: middle;
        border: 1rpx solid #00d1b6;
        height: 88rpx;
        line-height: 88rpx;
        border-radius: 44rpx;
        background: #00d1b6;
        color: #fff;
      }
    }
  }
  ::v-deep .u-popup {
    .u-popup__content {
      border-top-left-radius: 32rpx;
      border-top-right-radius: 32rpx;
      .u-picker {
        .u-toolbar {
          .u-toolbar__title {
            color: #222 !important;
            font-size: 32rpx;
            font-weight: 700;
          }
          .u-toolbar__confirm__wrapper {
            .u-toolbar__wrapper__confirm {
              color: #00d1b6 !important;
              font-size: 30rpx;
            }
          }
        }
        .u-picker__view {
          height: 350rpx !important;
          .u-picker__view__column {
            .u-picker__view__column__item {
              line-height: 34px !important;
            }
            &:nth-child(1) {
              display: block;
              flex: none;
              width: 260rpx;
            }
            &:nth-child(4),
            &:nth-child(5) {
              display: block;
              flex: none;
              width: 150rpx;
            }
          }
        }
      }
    }
  }
  ::v-deep .dosagePicker {
    .u-popup__content {
      border-top-left-radius: 32rpx;
      border-top-right-radius: 32rpx;
      .u-picker {
        .u-toolbar {
          .u-toolbar__title {
            color: #222 !important;
            font-size: 32rpx !important;
            font-weight: 700;
          }
          .u-toolbar__confirm__wrapper {
            .u-toolbar__wrapper__confirm {
              color: #00d1b6 !important;
              font-size: 30rpx;
            }
          }
        }
        .u-picker__view {
          height: 400rpx !important;
          .uni-picker-view-wrapper {
            .u-picker__view__column {
              &:nth-child(1) {
                display: block;
                flex: none;
                width: 350rpx;
              }
            }
          }
        }
      }
    }
  }
}
</style>
